import { Controller, Post, Body, UseGuards, Get, Req } from '@nestjs/common';
import { AuthService } from './auth.service';
import { CreateUserDto } from '../user/dto/create-user.dto';
import { LoginUserDto } from '../user/dto/login-user.dto';
import { ResponseUtil } from '../../common/utils/response.util';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import { generateClientId } from 'src/common/utils/client.util';
import { type Request } from 'express';

@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  /**
   * 用户注册
   * @param createUserDto 创建用户DTO
   * @returns 注册结果
   */
  @Post('register')
  async register(@Body() createUserDto: CreateUserDto, @Req() req: Request) {
    const captchaId = generateClientId(req);
    const result = await this.authService.register(createUserDto, captchaId);
    return ResponseUtil.success(result, '注册成功');
  }

  /**
   * 用户登录
   * @param loginUserDto 登录用户DTO
   * @returns 登录结果
   */
  @Post('login')
  async login(@Body() loginUserDto: LoginUserDto) {
    const result = await this.authService.login(loginUserDto);
    return ResponseUtil.success(result, '登录成功');
  }

  /**
   * 用户注销
   * @param req 请求对象
   * @returns 注销结果
   */
  @UseGuards(JwtAuthGuard)
  @Post('logout')
  async logout(@Req() req: { user: { id: string } }) {
    await this.authService.logout(req.user.id);
    return ResponseUtil.success(null, '注销成功');
  }

  /**
   * 获取当前用户信息
   * @param req 请求对象
   * @returns 用户信息
   */
  @UseGuards(JwtAuthGuard)
  @Get('profile')
  getProfile(@Req() req: { user: { id: string } }) {
    return ResponseUtil.success(req.user, '获取用户信息成功');
  }
}
